package com.danskin.wechat.web;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.github.pagehelper.util.StringUtil;
import com.danskin.wechat.entity.CustCouponDetail;
import com.danskin.wechat.entity.CustInfo;
import com.danskin.wechat.entity.ProductInfo;
import com.danskin.wechat.service.CustInfoService;
import com.danskin.wechat.service.SysAreaService;
import com.danskin.wechat.util.JsonUtils;
import com.danskin.wechat.util.Page;
/***
 * 会员
 * @author hanwei
 */
@Controller
@RequestMapping("custInfo")
public class CustInfoController extends BaseController{
	@Resource
	private CustInfoService custInfoService;	
	@Autowired
	private SysAreaService sysAreaService;
	/***
	 * 会员信息查询
	 * @param custInfo
	 * @return
	 */
	@RequestMapping(value = "getList", method = RequestMethod.GET)
	public String getList(CustInfo custInfo,Model model){
		return "custInfo/custInfo_list";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getCustInfoList", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object getCustInfoList(Page page,HttpServletRequest request) throws Exception {
		Map map = getRequestParameter(this.getRequest());
		map.put("mpId", this.getMpId());
		page.setMap(map);
		List<CustInfo> listCustInfo = custInfoService.getCustInfoList(page);
		return pagelistToJSONForBootStrapTable(queryCodeConversionName(listCustInfo), page);
	}

	/**
	 * 优惠券列表
	 * @param custInfo
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "queryCoupon", method = RequestMethod.GET)
	public String queryCoupon(CustCouponDetail custCouponDetail,Model model){
		List<CustCouponDetail> list = custInfoService.getCustCouponDetailList(custCouponDetail);
		model.addAttribute("list", list);
		return "custInfo/custCouponDetail_list";
	}
	/***
	 * 数据转化code-name
	 * @param listCustInfo
	 * @return
	 */
	private List<CustInfo> queryCodeConversionName(List<CustInfo> listCustInfo){
		List<CustInfo> list = new ArrayList<CustInfo>();
		if(listCustInfo.size()>0){
			for(CustInfo info:listCustInfo){
				CustInfo fo = new CustInfo();
				fo.setId(info.getId());
				fo.setMemberId(info.getMemberId());
				fo.setName(info.getName());
				fo.setMobile(info.getMobile());
				fo.setIdCardNo(info.getIdCardNo());
				fo.setGender(info.getGender());
				fo.setBirthday(info.getBirthday());
				fo.setProvince(sysAreaService.getSysAreaByCode(info.getProvince()));
				fo.setCity(sysAreaService.getSysAreaByCode(info.getCity()));
				fo.setDistrict(info.getDistrict());
				fo.setAddress(info.getAddress());
				fo.setQq(info.getQq());
				fo.setWeibo(info.getWeibo());
				fo.setHobby(info.getHobby());
				fo.setIdCardNo(info.getIdCardNo());
				fo.setJob(info.getJob());
				fo.setSource(info.getSource());
				fo.setCreatedTime(info.getCreatedTime());
				fo.setLastModifiedTime(info.getLastModifiedTime());
				fo.setHeadImgUrl(info.getHeadImgUrl());
				fo.setNickName(info.getNickName());
				fo.setVipLevel(info.getVipLevel());
				fo.setSubscribe(info.getSubscribe());
				fo.setTime(info.getTime());
				list.add(fo);
			}
		}
		return list;
	}
	/**
	 * 导出会员信息
	 * @param request
	 * @param response
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "exportExcelCustInfo", method = RequestMethod.GET)
	public void exportExcelCustInfo(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException{
		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
		String title = request.getParameter("name");
		String subscribe = request.getParameter("subscribe");
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		String mpId = String.valueOf(this.getMpId());
		String mobile = null;
		String name = null;
		if(StringUtil.isNotEmpty(title)){
			String tit = getConversionUTF(title);
			if(isNumeric(tit)){
				mobile = tit;
			}else{
				name = tit;
			}
		}
		List<CustInfo> listCustInfo = custInfoService.getCustInfoListExport(name,mobile,subscribe,startTime,endTime,mpId);
		HSSFWorkbook wb = new HSSFWorkbook();  
		HSSFSheet sheet = wb.createSheet("会员列表统计");
		HSSFRow row = sheet.createRow((int) 0);    
		HSSFCellStyle style = wb.createCellStyle();    
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式 
        HSSFCell cell = row.createCell((short) 0);    
        cell.setCellValue("昵称");    
        cell.setCellStyle(style);    
        cell = row.createCell((short) 1);    
        cell.setCellValue("姓名");    
        cell.setCellStyle(style);    
        cell = row.createCell((short) 2);    
        cell.setCellValue("手机号");    
        cell.setCellStyle(style);    
        cell = row.createCell((short) 3);    
        cell.setCellValue("性别");    
        cell.setCellStyle(style);       
        cell = row.createCell((short) 4);    
        cell.setCellValue("省份");    
        cell.setCellStyle(style);
        cell = row.createCell((short) 5);    
        cell.setCellValue("城市");    
        cell.setCellStyle(style);
        cell = row.createCell((short) 6);    
        cell.setCellValue("生日");    
        cell.setCellStyle(style);
        cell = row.createCell((short) 7);    
        cell.setCellValue("关注状态");    
        cell.setCellStyle(style);
        cell = row.createCell((short) 8);    
        cell.setCellValue("激活时间");    
        cell.setCellStyle(style);
        cell = row.createCell((short) 9);    
        cell.setCellValue("会员级别");    
        cell.setCellStyle(style);
        for (int i = 0; i < listCustInfo.size(); i++)  {
        	row = sheet.createRow((int) i + 1);  
        	CustInfo am = listCustInfo.get(i);
        	row.createCell((short) 0).setCellValue(am.getNickName());  
            row.createCell((short) 1).setCellValue(am.getName());  
            row.createCell((short) 2).setCellValue(am.getMobile());   
            if(am.getGender()==1){
            	row.createCell((short) 3).setCellValue("男"); 
            }
            if(am.getGender()==2){
            	row.createCell((short) 3).setCellValue("女"); 
            }
            if(StringUtil.isNotEmpty(am.getProvince())){
            	 row.createCell((short) 4).setCellValue(sysAreaService.getSysAreaByCode(am.getProvince())); 
            }
            if(StringUtil.isNotEmpty(am.getCity())){
            	row.createCell((short) 5).setCellValue(sysAreaService.getSysAreaByCode(am.getCity()));  
            }         
            if(am.getBirthday()!=null){
            	 cell = row.createCell((short) 6); 
            	 cell.setCellValue(dateFormater.format(am.getBirthday()));  
            }
            if(StringUtil.isNotEmpty(am.getSubscribe())){
            	if(am.getSubscribe().equals("1")){
                	row.createCell((short) 7).setCellValue("已关注");
                }else{
                	row.createCell((short) 7).setCellValue("未关注");
                } 
            }
            cell = row.createCell((short) 8);  
            if(am.getTime()!=null){
            	 cell.setCellValue(dateFormater.format(am.getTime()));  
            }
            row.createCell((short) 9).setCellValue(am.getVipLevel());  
        }
        OutputStream out = null;   
        try {        
            out = response.getOutputStream();    
            String fileName = "会员列表统计.xls";// 文件名        
            response.setContentType("application/x-download");
            response.setCharacterEncoding("utf-8"); 
            response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("gbk"), "iso8859-1"));
            wb.write(out);   
        } catch (Exception e) {    
            e.printStackTrace();    
        } finally {      
            try {       
                out.close();      
            } catch (IOException e) {      
                e.printStackTrace();    
            }      
        }   
	}
	/**
	 * 判断会员导出信息数据量大
	 * @param sku
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/checkExport", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String checkExport(String subscribe,String name,String startTime,String endTime) throws Exception {
    	Map<String,Object> map=new HashMap<String, Object>();
    	String mpId = String.valueOf(this.getMpId());
		String mobile = null;
		String newName = null;
		if(StringUtil.isNotEmpty(name)){
			if(isNumeric(name)){
				mobile = name;
			}else{
				newName = name;
			}
		}
    	List<CustInfo> listCustInfo = custInfoService.getCustInfoListExport(newName,mobile,subscribe,startTime,endTime,mpId);
    	if(listCustInfo.size()>=30000){	
    		map.put("status", 400);
    		map.put("msg", "导出数据超过3W条，请缩小日期范围");
    	}else{
    		map.put("status", 200);
    		map.put("msg", "可以导出");
    	}
    	return JsonUtils.objectToJson(map);
    }
	private  boolean isNumeric(String str){
	    Pattern pattern = Pattern.compile("[0-9]*");
	    return pattern.matcher(str).matches();   
	}

	// 处理中文乱码
	public String getConversionUTF(String str) throws UnsupportedEncodingException {
		if (!"".equals(str) && str != null) {
			str = new String(str.getBytes("iso-8859-1"), "UTF-8");
		}
		return str;
	}
}
